import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    userInfo: {
      name: '',
      avatar: ''
    }
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER_INFO: (state, info) => {
      state.userInfo = info
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      return login(userInfo).then(data => {
        setToken(data.token)
        commit('SET_TOKEN', data.token)
        commit('SET_USER_INFO', data.userInfo)
      })
    },

    // 获取用户信息
    GetInfo ({ commit }) {
      return getInfo().then(data => {
        commit('SET_USER_INFO', data)
        return data
      })
    },

    // 登出
    LogOut ({ commit, state }) {
      return logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        removeToken()
      })
    }
  }
}

export default user
